TypeScript で Base64 と Hex を相互変換
Hex → Base64
code:hexToBase64.ts
const hexToBase64 = (hex: string) =>
btoa(
String.fromCharCode(
...(hex.match(/0-9a-f{2}/gi) ?? []).map((c) => parseInt(c, 16)) )
);
Base64 → Hex
code:base64ToHex.ts
const base64ToHex = (base64: string) =>
.map((c) => c.charCodeAt(0).toString(16).padStart(2, "0"))
.join("");
テスト
code:test.ts
/**
* test 1
*/
{
const base46Str = "B9PlPiWDr2Ve2EpZVvBL";
console.log(base64ToHex(base46Str));
console.assert(hexToBase64(base64ToHex(base46Str)) === base46Str);
}
/**
* test 2
*/
{
const hexString = "a0eebc999c0b4ef8bb6d6bb9bd380a11";
console.log(hexToBase64(hexString));
console.assert(base64ToHex(hexToBase64(hexString)) === hexString);
}
uuid.parse するとよさそう?
ビット演算するのか
- 有無は気にしない?